<!--获取code-->
<template>
  <div class="get-code-box">
    <img src="../../static/image/getCodeLogo.png">
    <!-- <div @click="codeClick">
      获取code
    </div>
    <div>code：{{wechatCode}}</div>
    <div>openId：{{openId}}</div>
    <div>routerUrl：{{routerUrl}}</div>
    <div @click="idClick">
      跳转首页
    </div> -->
  </div>
</template>

<script>
import { requestApi, appId } from "@/utils/config";
export default {
  name: 'GetCode',
  components: {
  },
  data () {
    return {
      routerUrl: null, //获取id后跳转的页面
      wechatCode: null,
      openId: null,
      loading: false,
      pageType: null,
    };
  },
  async onShow () {

  },
  async onLoad (e) {
    var vm = this;
    vm.pageType = e.pageType && e.pageType == 'index' ? e.pageType : null
    vm.routerUrl = uni.getStorageSync('routerUrl')
    vm.openId = uni.getStorageSync('openId')
    // alert(vm.openId)
    // alert(location.href)
    // 有id直接返回首页（针对表单页返回到此页的操作）
    if (vm.openId) {
      uni.redirectTo({
        url: '/pages/index/index'
      });
    } else {
      vm.getCode()
    }
    // vm.wechatCode = vm.getUrlCode().code; // 截取code
    // if (vm.wechatCode) {
    //   vm.getOpenId(vm.wechatCode)
    // }
  },
  created () { },
  methods: {
    codeClick () {
      var vm = this;
      vm.getCode()
      // alert(location.href)
    },
    idClick () {
      var vm = this;
      uni.redirectTo({
        url: '/pages/index/index'
      });
    },
    getCode () {
      var vm = this;
      if (!vm.func.isWeixin()) return;
      // vm.loading = true
      uni.showLoading({
        title: '加载中...',
        mask: true
      });
      var local = encodeURIComponent(requestApi + '/#/pages/getCode/index'); // 当前H5页面的url（必须使用encodeuricomponent()函数进行解码）
      var appid = appId; //公众号的appid
      vm.wechatCode = vm.getUrlCode().code; // 截取code
      if (!vm.wechatCode || vm.wechatCode === '' || vm.wechatCode == undefined) { //需要判空,不然会一直重复请求
        var wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid +
          '&redirect_uri=' + local +
          '&response_type=code' +
          '&scope=snsapi_base' +
          '&state=0#wechat_redirect';
        window.location.href = wxUrl;
      } else {
        // uni.setStorageSync('wechatCode', vm.wechatCode)
        vm.getOpenId(vm.wechatCode)
        // uni.reLaunch({
        //   url: '/pages/index/index'
        // });

      }
    },
    getUrlCode () {
      var url = location.href; //获取打开的公众号的路径
      var theRequest = new Object();
      if (url.indexOf('?') != -1) {
        var str = url.substr(url.indexOf('?') + 1);
        var strs = str.split('&');
        for (var i = 0; i < strs.length; i++) {
          var items = strs[i].split('=');
          theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
        }
      }
      return theRequest;
    },
    getOpenId (code) {
      var vm = this
      // alert(code)
      vm.tui.request('/api/wx/getopenid', 'get', { code: code }, false, false, false, true).then((res) => {
        uni.hideLoading()
        // alert(JSON.stringify(res))
        // vm.openId = JSON.stringify(res)
        // vm.openId = JSON.stringify(res.data[0])
        if (res.code == 200) {
          vm.openId = res.data[0].openid
          // uni.setStorageSync('wechatCode', vm.wechatCode)
          uni.setStorageSync('openId', vm.openId)
          if (vm.pageType && vm.pageType == 'index') {
            vm.subscribeopenid()
          } else {
            uni.redirectTo({
              url: vm.routerUrl
            });
          }
        }
      }).catch((e) => { })
    },
    // 订阅推送-默认订阅【针对 停气通知】
    subscribeopenid () {
      var vm = this;
      vm.tui.request('/api/subscribeopenid/add', 'post', { 'openid': uni.getStorageSync('openId') }, false, false, false).then((res) => {
        vm.func.showToast('正在跳转中...')
        vm.getSubscribe()
      }).catch((e) => { })
    },
    async getSubscribe () {
      var vm = this, data = null
      vm.tui.request('/api/subscribeopenid/list', 'POST', { 'openid': uni.getStorageSync('openId') }, false, false, val).then((res) => {
        if (res.code == 200) {
          data = res.data.length ? res.data[0].status : null
          if (data == 1) {
            // 跳 停气通知 页面
            uni.redirectTo({
              url: vm.routerUrl
            });
          }
        }
      }).catch((e) => { })
    },
  },
  mounted () {
  },
  // async onUnload () {
  //   uni.setStorageSync('wechatCode', '')
  //   uni.setStorageSync('openId', '')
  // },
  // beforeDestroy () {
  //   uni.setStorageSync('wechatCode', '')
  //   uni.setStorageSync('openId', '')
  // },
};
</script>

<style lang="scss" scoped>
.get-code-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    width: 60%;
    opacity: 0.5;
  }
  > div {
    padding: 30px;
  }
}
</style>
<style>
page {
  width: 100%;
  height: 100%;
  background: #fff;
}
</style>
